import { post } from '@/utils/request';
import { Effect } from 'dva';
import { Reducer } from 'redux';
import * as api from '@/constants/api';

export interface CurrentUser extends BaseModel {
  account?: string;
  role?: string;
  name?: string;
  avatar?: string;
}

export interface UserModelState {
  currentUser?: CurrentUser;
}

export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetchCurrent: Effect;
    updateProfile: Effect;
    // updateSpecialStu: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    saveProfile: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    *fetchCurrent(_, { call, put }) {
      const response = yield post(api.GET_USERINFO);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *updateProfile({ payload }, { call, put }) {
      const response = yield post(api.UPDATE_PROFILE, { ...payload });

      yield put({
        type: 'saveProfile',
        payload,
      });

      return true;
    },
    // *updateSpecialStu({payload}, {call ,put}){
    //   const response = yield post(api.UPDATE_PROFILE, {...payload});

    //   yield put({
    //     type: 'saveProfile',
    //     payload,
    //   })

    //   return true;
    // }
  },

  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    saveProfile(state, action) {
      return {
        ...state,
        currentUser: {
          ...state?.currentUser,
          ...action.payload,
        },
      };
    },
  },
};

export default UserModel;
